package io.yakult.sfa.sing_box_for_flutter

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.VpnService
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.MethodChannel
import io.nekohasekai.sfa.Application
import io.nekohasekai.sfa.bg.ServiceConnection
import io.nekohasekai.sfa.bg.ServiceNotification
import io.nekohasekai.sfa.constant.Alert
import io.nekohasekai.sfa.constant.ServiceMode
import io.nekohasekai.sfa.constant.Status
import io.nekohasekai.sfa.database.Settings
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

class MainActivity : FlutterActivity(), ServiceConnection.Callback {
    private val connection = ServiceConnection(this, this)
    val serviceStatus = MutableLiveData(Status.Stopped)

    companion object {
        const val REQUEST_CODE_VPN = 100
        const val REQUEST_CODE_PERMISSION = 101
        const val CHANNEL_NAME = "vpn_plugin" // 通道名称，与Flutter插件中定义的相同
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 创建一个MethodChannel
        flutterEngine?.dartExecutor?.binaryMessenger?.let {
            val methodChannel = MethodChannel(it, CHANNEL_NAME)
            // 设置方法处理程序
            methodChannel.setMethodCallHandler { call, result ->
                if (call.method == "startVpn") {
                    // 处理来自Flutter的方法调用
                    android.util.Log.e("===========", "startVpn from flutter")
                    startVpn(call.argument("configJson"))
                    result.success(null) // 可以返回结果给Flutter
                } else if (call.method == "stopVpn") {
                    // 处理来自Flutter的方法调用
                    android.util.Log.e("===========", "stopVpn from flutter")
                    stopVpn()
                    result.success(null) // 可以返回结果给Flutter
                } else {
                    result.notImplemented()
                }
            }
        }
    }

    private fun startVpn(configJson: String?) {
        configJson?.let {
            if (it.isNotEmpty()) {
                val configFile = File(filesDir, "config.json")
                if (!configFile.exists()) {
                    configFile.writeText(it)
                }
            }
        }
        startService()
    }

    private fun stopVpn() {
        sendBroadcast(android.content.Intent(io.nekohasekai.sfa.constant.Action.SERVICE_CLOSE))
    }

    fun reconnect() {
        connection.reconnect()
    }

    @SuppressLint("NewApi")
    fun startService() {
        if (!ServiceNotification.checkPermission()) {
            val permission = Manifest.permission.POST_NOTIFICATIONS
            if (ContextCompat.checkSelfPermission(
                    this,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(permission),
                    REQUEST_CODE_PERMISSION
                )
            } else {
                startService()
            }
            return
        }
        lifecycleScope.launch(Dispatchers.IO) {
            if (Settings.rebuildServiceMode()) {
                reconnect()
            }
            if (Settings.serviceMode == ServiceMode.VPN) {
                if (prepare()) {
                    return@launch
                }
            }
            val intent = Intent(Application.application, Settings.serviceClass())
            withContext(Dispatchers.Main) {
                ContextCompat.startForegroundService(Application.application, intent)
            }
        }
    }

    private suspend fun prepare() = withContext(Dispatchers.Main) {
        try {
            val intent = VpnService.prepare(this@MainActivity)
            if (intent != null) {
                startActivityForResult(intent, REQUEST_CODE_VPN)
                true
            } else {
                false
            }
        } catch (e: Exception) {
            onServiceAlert(Alert.RequestVPNPermission, e.message)
            false
        }
    }

    override fun onServiceStatusChanged(status: Status) {
        serviceStatus.postValue(status)
    }

    override fun onServiceAlert(type: Alert, message: String?) {
        val builder = MaterialAlertDialogBuilder(this)
        builder.setPositiveButton(android.R.string.ok, null)
        when (type) {
            Alert.RequestVPNPermission -> {
                builder.setMessage(getString(R.string.service_error_missing_permission))
            }

            Alert.RequestNotificationPermission -> {
                builder.setMessage(getString(R.string.service_error_missing_notification_permission))
            }

            Alert.EmptyConfiguration -> {
                builder.setMessage(getString(R.string.service_error_empty_configuration))
            }

            Alert.StartCommandServer -> {
                builder.setTitle(getString(R.string.service_error_title_start_command_server))
                builder.setMessage(message)
            }

            Alert.CreateService -> {
                builder.setTitle(getString(R.string.service_error_title_create_service))
                builder.setMessage(message)
            }

            Alert.StartService -> {
                builder.setTitle(getString(R.string.service_error_title_start_service))
                builder.setMessage(message)

            }
        }
        builder.show()
    }

    override fun onServiceWriteLog(message: String?) {
    }

    override fun onServiceResetLogs(messages: MutableList<String>) {
    }

    override fun onDestroy() {
        connection.disconnect()
        super.onDestroy()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_VPN) {
            if (resultCode == RESULT_OK) {
                startService()
            } else {
                onServiceAlert(Alert.RequestVPNPermission, null)
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE_PERMISSION) { // 检查请求码是否匹配
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了通知权限
                startService()
            } else {
                // 用户拒绝了通知权限
                onServiceAlert(Alert.RequestNotificationPermission, null)
            }
        }
    }
}